<template>
    <div class="container">
        <div class="grid">
            <table class="grid-background" :style="gridBackgroundStyles">
                <tr v-for="_ in (grid - 1)">
                    <td v-for="_ in (grid - 1)"></td>
                </tr>
            </table>
            <table class="grid-space" :style="gridSpaceStyles">
                <tr v-for="(item, y) in gridData" :key="y">
                    <td :data-x="x" :data-y="y" v-for="(val, x) in item" :key="x" class="regular" :class="{'regular-white': val === 1, 'regular-black': val === 2}" @click="handleClick(x, y)"></td>
                </tr>
            </table>
        </div>
    </div>
</template>

<script>
import {defineComponent} from "vue";
// import {checkGameOver} from "@/assets/js/checkerboard.js";
import axios from "axios";
import {ElMessage} from "element-plus";
export default defineComponent({
    data(){
        return {
            grid: 15,
            gridData: null,
            gridBackgroundStyles: {
                '--containerSize': '0px',
            },
            gridSpaceStyles: {
                '--containerSize': '0px',
            },
            chessName: {
                1: '白棋',
                2: '黑棋'
            },
            isOver: false,      //是否结束
            myTurn: false,      //是否为我的回合
            myChess: 0,         //我的棋子颜色
        }
    },
    props:{
        socket: {
            type: WebSocket,
        },
        isStart: {          //是否开始游戏
            type: Boolean,
            default: false,
        },
        roundType: {    //是否为我的回合
            type: Boolean,
            default: false,
        },
        opposingBoard: {            //对方的棋盘
            type: Array,
            default: []
        },
        chess: {            //我的棋子颜色
            type: Number,
            default: 0,
        },
        isGameOver:{
            type: Boolean,
            default: false,
        }
    },
    watch: {
        opposingBoard(newValue) {
            this.gridData = newValue;
        },
        roundType(newValue) {
            this.myTurn = newValue;
        },
        chess(newValue) {
            this.myChess = newValue;
        },
        isGameOver(newValue) {
            this.isOver = newValue;
        },
    },
    beforeMount() {
        this.gridData = Array(this.grid).fill(Array(this.grid).fill(0))
        this.changeLayout();
    },
    mounted() {
        this.initGridData();
    },
    methods: {
        initGridData() {
            this.changeContainerWidthHeight();
        },
        changeContainerWidthHeight() {
            window.onresize = this.$common.debounce(this.changeLayout);
        },
        changeLayout(){
            let size =  Math.min(...[window.innerWidth, window.innerHeight]) - 40;
            this.gridSpaceStyles = {
                '--containerSize': `${size}px`,
                '--containerTranslate': `-${(size / this.grid) * (this.grid - 1)}px`,
            }
            this.gridBackgroundStyles = {
                '--containerSize': `${(size / this.grid) * (this.grid - 1)}px`,
                '--translateXY': `${(size / this.grid) / 2}px`,
            }
        },
        handleClick(x, y){
            if(this.isOver || !this.isStart){
                return;
            }
            if(this.gridData[y][x] !== 0){
                return;
            }
            if(!this.myTurn){
                return
            }
            this.gridData = this.gridData.map((rowArr, rowIndex) => {
                if (rowIndex === y) {
                    return rowArr.map((cell, cellIndex) => {
                        return cellIndex === x ? this.myChess : cell;
                    });
                } else {
                    return rowArr; // 其他行保持原值
                }
            }); // 更新board数组
            this.$emit('changeRoundType');
            // if(checkGameOver(this.gridData, [x, y], this.gridData[y][x])){
            //     this.isOver = true;
            // }
            this.$emit('recordMatching', {data: this.gridData, x: x, y: y}, this.myChess, this.myChess);
            // this.recordMatching();
        },
        async recordMatching(result){
            const response = await axios.post('/api/recordmatching', {room_id: this.$common.getSessionStorageValues('roomInfo.room_id'), board: JSON.stringify(this.gridData), result: this.isOver ? 1 : 0, chess: this.myChess }, {
                headers: {
                    token: this.$common.getSessionStorageValues('tokenData.token'),
                    refreshtoken: this.$common.getSessionStorageValues('tokenData.refreshtoken')
                }
            });
            if (response.data.code === 200 && response.status === 200) {
                this.socket.send(JSON.stringify({
                    mode: 'matching',
                    room_id: this.$common.getSessionStorageValues('roomInfo.room_id'),
                    uid: this.$common.getSessionStorageValues('userLoginInfo.id'),
                    board: this.gridData,
                    chess: this.myChess,
                    board_md5: response.data.data.board_md5 ? response.data.data.board_md5 : '',
                }))
            } else {
                ElMessage({
                    message: response.data.msg ? response.data.msg : '错误',
                    type: 'warning',
                })
            }
            if(this.isOver){
                const response = await axios.post('/api/processingresults', {room_id: this.$common.getSessionStorageValues('roomInfo.room_id'), result: result ? result : this.myChess}, {
                    headers: {
                        token: this.$common.getSessionStorageValues('tokenData.token'),
                        refreshtoken: this.$common.getSessionStorageValues('tokenData.refreshtoken')
                    }
                });
                if (response.data.code === 200 && response.status === 200) {
                    this.socket.send(JSON.stringify({
                        mode: 'processingResults',
                        room_id: this.$common.getSessionStorageValues('roomInfo.room_id'),
                        uid: this.$common.getSessionStorageValues('userLoginInfo.id'),
                    }))
                } else {
                    ElMessage({
                        message: response.data.msg ? response.data.msg : '错误',
                        type: 'warning',
                    })
                }
            }
        }
    },
});
</script>

<style lang="scss" scoped>
    .container{
        width: fit-content;
        height: 100vh;
        .grid{
            width: fit-content;
            height: 100vh;
            padding: 20px;
            position: relative;
            table{
                transition: 0.5s ease;
                border-collapse: collapse;
                td{
                    border: 1px solid #ABABAB;
                    padding: 0;
                }
            }
            .grid-background{
                width: var(--containerSize, 0);
                height: var(--containerSize, 0);
                transform: translate(var(--translateXY, 0), var(--translateXY, 0));
                tr:nth-child(8n-4) td:nth-child(8n-4), tr:nth-child(8) td:nth-child(8){
                    position: relative;;
                    &::before{
                        --BlackDotSize: calc(var(--containerSize, 0) / 80);
                        display: block;
                        width: var(--BlackDotSize);
                        height: var(--BlackDotSize);
                        background-color: black;
                        content: "";
                        border-radius: 50%;
                        position: absolute;
                        top: calc(var(--BlackDotSize) / 2 * -1);
                        left: calc(var(--BlackDotSize) / 2 * -1);
                    }
                }
            }
            .grid-space{
                width: var(--containerSize, 0);
                height: var(--containerSize, 0);
                transform: translate(0, var(--containerTranslate, 0)) scaleY(-1);
                td{
                    border: none;
                    text-align: center;
                    transform: scaleY(-1);
                }
                td.regular::before{
                    --DotSize: calc(var(--containerSize, 0) / 80);
                    width: var(--DotSize);
                    height: var(--DotSize);
                    margin: auto;
                    display: block;
                    content: "";
                    background-color: unset;
                    border-radius: 50%;
                }
                td.regular-white::before{
                    width: 80%;
                    height: 80%;
                    display: block;
                    background: url('@/assets/image/white.png') 0 0 / 100% no-repeat;
                    filter: drop-shadow(5px 5px 5px #888888);
                }
                td.regular-black::before{
                    width: 80%;
                    height: 80%;
                    display: block;
                    background: url('@/assets/image/black.png') 0 0 / 100% no-repeat;
                    filter: drop-shadow(5px 5px 5px #888888);
                }
            }
        }
    }
</style>